package com.zwb.service.handlers;

/**
 * @author 头发又黑又长
 * @Date 2022/9/1 16:05
 * @email zwb15083976291@163.com
 */

import com.zwb.service.enums.StatusCode;
import com.zwb.service.exception.NotLoggedInException;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

/**
 * 决策管理器
 */

public class AccessDecisionManagerImpl implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        // 当前角色权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        // 遍历当前接口需要的权限
        for (ConfigAttribute configAttribute : configAttributes) {

            // 当前url需要的角色
            String needRole = configAttribute.getAttribute();

            // 只需要登录即可访问的接口，此角色在安全数据源中设置
            if ("ROLE_LOGIN".equals(needRole)) {
                // 判断用户是否登录
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new NotLoggedInException(StatusCode.NO_LOGIN.getMessage());
                }
                return;
            }
            // 权限判断 : 判断用户角色是否为 URL 角色
            for (GrantedAuthority authority : authorities) {
                if (needRole.equals(authority.getAuthority())) {
                    return;
                }
            }
        }
        // 匹配失败返回异常
        throw new AccessDeniedException(StatusCode.AUTHORIZED.getMessage());
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
